/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package korekosystem.vista;

import java.awt.Point;
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;
//import javax.management.Query;
import javax.persistence.*;
import javax.swing.JOptionPane;
import javax.swing.event.InternalFrameAdapter;
import javax.swing.event.InternalFrameEvent;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;
import korekosystem.modelo.Producto;
import net.coderazzi.filters.gui.TableFilterHeader;
import korekosystem.JTextFieldLimit;
import korekosystem.modelo.Tipoproducto;
/**
 *
 * @author Santiago
 */
public class ABMProducto extends javax.swing.JInternalFrame {

    
    @PersistenceContext
    EntityManager entityMgr;
   
    Producto producto;
    Boolean multipleSeleccion;
    /**
     * Creates new form ABMProducto
     */
    public ABMProducto() {
        initComponents();
        nombreText.setDocument(new JTextFieldLimit(30));
        descripcionText.setDocument(new JTextFieldLimit(40));
        TableFilterHeader tablefilter = new TableFilterHeader(jTable1);
     this.addInternalFrameListener(new InternalFrameAdapter() {
            
            // Cierra el entityManager cuando se cierra
            // la ventana
            @Override
            public void internalFrameClosed(InternalFrameEvent ev) {
                if (entityMgr != null && entityMgr.isOpen()) {
                    entityMgr.close();
                }
            }
            // Se reescribe el evento cuando se abre la ventana
            // para que instancie el entityManager
            @Override
            public void internalFrameOpened(InternalFrameEvent ev) {
                ABMProducto estaVentana =
                        (ABMProducto) ev.getSource();
                try {
                    entityMgr = Persistence
                            .createEntityManagerFactory("KorekoSystemPU")
                            .createEntityManager();
                    estaVentana.recargarTabla();
                } catch (Exception e) {
                    JOptionPane.showMessageDialog(estaVentana,
                            "Error al inciar el motor de persistencia\n [" +
                            e.getMessage() + "]");
                    estaVentana.dispose();
                }
            }
        });
    
    
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        nombreText = new javax.swing.JTextField();
        descripcionText = new javax.swing.JTextField();
        pendienteCheck = new javax.swing.JCheckBox();
        stockText = new javax.swing.JFormattedTextField();
        jLabel2 = new javax.swing.JLabel();
        tipoComboBox = new javax.swing.JComboBox();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        guardarButton = new javax.swing.JButton();
        eliminarButton = new javax.swing.JButton();

        setClosable(true);
        setIconifiable(true);
        setMaximizable(true);
        setTitle("ABMProducto");
        addInternalFrameListener(new javax.swing.event.InternalFrameListener() {
            public void internalFrameOpened(javax.swing.event.InternalFrameEvent evt) {
                formInternalFrameOpened(evt);
            }
            public void internalFrameClosing(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameClosed(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameIconified(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameDeiconified(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameActivated(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameDeactivated(javax.swing.event.InternalFrameEvent evt) {
            }
        });

        jPanel1.setBorder(javax.swing.BorderFactory.createEtchedBorder());

        jLabel1.setText("Nombre:");

        jLabel3.setText("Descripción:");

        jLabel4.setText("Pendiente de Compra:");

        jLabel5.setText("Stock:");

        nombreText.setHorizontalAlignment(javax.swing.JTextField.LEFT);

        pendienteCheck.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                pendienteCheckActionPerformed(evt);
            }
        });

        try {
            stockText.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("####")));
        } catch (java.text.ParseException ex) {
            ex.printStackTrace();
        }
        stockText.setFocusLostBehavior(javax.swing.JFormattedTextField.PERSIST);
        stockText.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                stockTextActionPerformed(evt);
            }
        });

        jLabel2.setText("Tipo:");

        tipoComboBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
        tipoComboBox.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                tipoComboBoxMouseClicked(evt);
            }
        });
        tipoComboBox.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                tipoComboBoxItemStateChanged(evt);
            }
        });
        tipoComboBox.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                tipoComboBoxActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel3)
                    .addComponent(jLabel1)
                    .addComponent(jLabel2))
                .addGap(10, 10, 10)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(nombreText, javax.swing.GroupLayout.DEFAULT_SIZE, 352, Short.MAX_VALUE)
                    .addComponent(descripcionText)
                    .addComponent(tipoComboBox, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addGap(22, 22, 22)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jLabel5)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(stockText))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jLabel4)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(pendienteCheck)))
                .addGap(24, 24, 24))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
                    .addComponent(nombreText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel1)
                    .addComponent(jLabel4)
                    .addComponent(pendienteCheck))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel5)
                    .addComponent(jLabel3)
                    .addComponent(descripcionText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(stockText, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(tipoComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap())
        );

        jScrollPane1.setBorder(javax.swing.BorderFactory.createEtchedBorder());

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null},
                {null, null, null, null, null, null, null}
            },
            new String [] {
                "", "id", "Nombre", "Descripción", "Tipo", "Stock", "Pendiente de Compra"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.Boolean.class, java.lang.Integer.class, java.lang.String.class, java.lang.String.class, java.lang.Object.class, java.lang.Long.class, java.lang.Boolean.class
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }
        });
        jTable1.getTableHeader().setReorderingAllowed(false);
        jTable1.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jTable1MouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(jTable1);
        jTable1.getColumnModel().getColumn(0).setMinWidth(40);
        jTable1.getColumnModel().getColumn(0).setMaxWidth(40);
        jTable1.getColumnModel().getColumn(5).setMinWidth(60);
        jTable1.getColumnModel().getColumn(5).setPreferredWidth(60);

        guardarButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/recursos/guardar.png"))); // NOI18N
        guardarButton.setText("Guardar");
        guardarButton.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                guardarButtonMouseClicked(evt);
            }
        });

        eliminarButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/recursos/eliminar.png"))); // NOI18N
        eliminarButton.setText("Eliminar");
        eliminarButton.setEnabled(false);
        eliminarButton.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                eliminarButtonMouseClicked(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 614, Short.MAX_VALUE)
                    .addComponent(jPanel1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGap(0, 0, Short.MAX_VALUE)
                        .addComponent(guardarButton)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(eliminarButton)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 267, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 28, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(guardarButton)
                    .addComponent(eliminarButton))
                .addGap(8, 8, 8))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void pendienteCheckActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_pendienteCheckActionPerformed
        // TODO add your handling code here:
        
    }//GEN-LAST:event_pendienteCheckActionPerformed

    private void jTable1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTable1MouseClicked
         // La salsa y el fideo a full aca, cuidado cuidado...
        // apartir de este salto de linea, usted entra en un universo alterno
        
        // esto sirve para que efectivamente tome en cuenta solo los
        // clicks en la primera columna (la columna de seleccion)
        Point p = evt.getPoint();
        if (jTable1.columnAtPoint(p) == 0){
            // Recorremos toda la tabla, buscando los seleccionados
            // guardamos el numero de elementos seleccionados
            // si es uno solo, cargamos en producto.
            TableModel tm = jTable1.getModel();
            int selectcount = 0;
            int selectindex = 0;
            for (int i=0; i < tm.getRowCount(); i++ ){
                if( (Boolean) tm.getValueAt(i, 0) == true){
                    selectcount++;
                    selectindex = i;
                }

            }

            if(selectcount == 1){
                Integer id = new Integer(tm.getValueAt(selectindex, 1).toString());

                if ( entityMgr.isOpen()) {
                    try {
                        Query q = entityMgr
                                .createQuery("select o from Producto o " +
                                        "where trim(o.id) = :codigo");
                        q.setParameter("codigo", id.toString());
                        producto = (Producto) q.getSingleResult();
                        // puede que el objeto no esté sincronizado con la bd
                        entityMgr.refresh(producto);

                    }
                    catch (NoResultException  ignorada) {}
                    catch (Exception e) {
                        JOptionPane.showMessageDialog(this, "Error del sistema: [" +
                                e.getMessage() + "]");
                        e.printStackTrace();
                    }
                }

                this.rellenarCampos();
                eliminarButton.setEnabled(true);
                multipleSeleccion = false;
                
            //si no hay nada seleccionado, limpiamos el formulario
            }else if (selectcount == 0){
                eliminarButton.setEnabled(false);
                limpiarFormulario();
                producto = null;
                multipleSeleccion = false;
            //mas de 1...
            }else{
                eliminarButton.setEnabled(true);
                limpiarFormulario();
                producto = null;
                multipleSeleccion = true;
            }
          
        }
        
        
        
    }//GEN-LAST:event_jTable1MouseClicked

    private void eliminarButtonMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_eliminarButtonMouseClicked
         // Acciones para cuando se hace Click en Eliminar
        if(producto != null || multipleSeleccion) {
            int r = JOptionPane.showConfirmDialog(this, "Esta seguro de " +
                    "borrar los datos", "Atencion", JOptionPane.YES_NO_OPTION);
            if (r == JOptionPane.NO_OPTION) {
                return;
            }
            
            EntityTransaction tr = null;
            try {
                tr = entityMgr.getTransaction();
                tr.begin();
                if(!multipleSeleccion){
                    entityMgr.remove(producto);
                }else{
                    List<Producto> lista = devolverSeleccionados();
                    for (Producto c : lista){
                        entityMgr.remove(c);
                    }
                }
                
                tr.commit();
            }
            catch (Exception e) {
                if (tr != null && tr.isActive()) {
                   tr.rollback();
                }                
                JOptionPane.showMessageDialog(this, "Error del sistema: [" +
                    e.getMessage() + "]");
                e.printStackTrace();
                
            } finally{
                producto = null;
                limpiarFormulario();
                recargarTabla();
            }
        }
      
    }//GEN-LAST:event_eliminarButtonMouseClicked

    private void guardarButtonMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_guardarButtonMouseClicked
        // TODO add your handling code here:
         // Avisamos que ciertos campos no pueden ser nulos
        if(nombreText.getText() == null || nombreText.getText().trim().equals("")) {
            JOptionPane.showMessageDialog(this, "El nombre no puede ser nulo");
            nombreText.requestFocus();
            return;
        } else if(stockText.getText() == null || 
                stockText.getText().trim().equals("")) {
            JOptionPane.showMessageDialog(this, "El stock no puede ser nulo");
            stockText.requestFocus();
            return;
        }
        
        
        EntityTransaction tr = null;
        try {
            tr = entityMgr.getTransaction();
            tr.begin();
            // si el id de la bd es nulo el objeto no existe
            if (producto == null) {
                producto = new Producto();
                producto.setNombre(nombreText.getText().trim());
                producto.setDescripcion(descripcionText.getText().trim());
                producto.setStock(Long.valueOf(stockText.getText().trim()));
                producto.setTipo((Tipoproducto)tipoComboBox.getSelectedItem());
                System.out.print("El doble del producto es"+producto.getStock()*2);
                
                if (pendienteCheck.isSelected()){ //verifica si está marcado la casilla de pendiente
                    producto.setPendiente(true);
                } else {
                    producto.setPendiente(false);
                }
                entityMgr.persist(producto);
            } else {
                producto.setNombre(nombreText.getText().trim());
                producto.setDescripcion(descripcionText.getText().trim());
                producto.setStock(Long.valueOf(stockText.getText().trim()));
                producto.setTipo((Tipoproducto)tipoComboBox.getSelectedItem());
                System.out.print("El doble del producto es"+producto.getStock()*2);
                
                if (pendienteCheck.isSelected()){ //verifica si está marcado la casilla de pendiente
                    producto.setPendiente(true);
                } else {
                    producto.setPendiente(false);
                }
                    
                entityMgr.merge(producto);   
            }
            tr.commit();
            JOptionPane.showMessageDialog(this, "Cambios guardados con exito!");
            
        } catch (Exception e) {
            if (tr != null && tr.isActive()) {
                tr.rollback();
            }
            JOptionPane.showMessageDialog(this, "Error del sistema: [" +
                        e.getMessage() + "]");
            e.printStackTrace();
        }finally{
            producto = null;
            limpiarFormulario();
            recargarTabla();
            eliminarButton.setEnabled(false);
        }
    }//GEN-LAST:event_guardarButtonMouseClicked

    private void stockTextActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_stockTextActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_stockTextActionPerformed

    private void tipoComboBoxMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tipoComboBoxMouseClicked
        // TODO add your handling code here:
    }//GEN-LAST:event_tipoComboBoxMouseClicked

    private void tipoComboBoxItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_tipoComboBoxItemStateChanged
        // TODO add your handling code here:
 
    }//GEN-LAST:event_tipoComboBoxItemStateChanged

    private void tipoComboBoxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_tipoComboBoxActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_tipoComboBoxActionPerformed

    private void formInternalFrameOpened(javax.swing.event.InternalFrameEvent evt) {//GEN-FIRST:event_formInternalFrameOpened
        // Rellenamos todo:
        llenarCBTipo();
        limpiarFormulario();
    }//GEN-LAST:event_formInternalFrameOpened

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JTextField descripcionText;
    private javax.swing.JButton eliminarButton;
    private javax.swing.JButton guardarButton;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTable1;
    private javax.swing.JTextField nombreText;
    private javax.swing.JCheckBox pendienteCheck;
    private javax.swing.JFormattedTextField stockText;
    private javax.swing.JComboBox tipoComboBox;
    // End of variables declaration//GEN-END:variables

 public void recargarTabla(){
        try{
            Query q = entityMgr.createNamedQuery("Producto.findAll");
            List<Producto> result = q.getResultList();
            // se obtiene la referencia al modelo de datos
            DefaultTableModel tm = ((DefaultTableModel)jTable1.getModel());
            // se descartan la filas existentes
            tm.setRowCount(0);

            // se añaden los datos obtenidos si es que existen
            // cada fila recuperada es un array de Object[]
            for (Producto o : result) {
                // Agregamos a un vector las propiedades
                Vector v = new Vector();
                v.add(false);
                v.add(o.getId());
                v.add(o.getNombre());
                v.add(o.getDescripcion());
                v.add(o.getTipo());
                v.add(o.getStock());
                v.add(o.getPendiente());
                
                
                // Agregamos ese vector como columna
                tm.addRow(v);
            }
        }catch(Exception e){
            JOptionPane.showMessageDialog(this,
                            "Error en el sistema\n [" +
                            e.getMessage() + "]");
                    this.dispose();
        }
    }

    private void rellenarCampos() {
        if (producto != null && producto.getId() != null){
            this.nombreText.setText(producto.getNombre());
            this.descripcionText.setText(producto.getDescripcion());
            this.stockText.setText(String.valueOf(producto.getStock()));
            this.pendienteCheck.setSelected(producto.getPendiente());
            this.tipoComboBox.setSelectedItem(producto.getTipo());
        }
    }

    private void limpiarFormulario() {
            this.nombreText.setText("");
            this.descripcionText.setText("");
            this.stockText.setText("");
            this.pendienteCheck.setSelected(false);
            this.tipoComboBox.setSelectedIndex(-1);
           
    }
    
 /*
  * Se encarga de devolver el item seleccionado de la tabla
  * 
  */
 private List<Producto> devolverSeleccionados(){
        TableModel tm = jTable1.getModel();
        ArrayList<Producto> lista = new ArrayList();
        for (int i=0; i < tm.getRowCount(); i++ ){
                if( (Boolean) tm.getValueAt(i, 0) == true){
                    Integer id = new Integer(tm.getValueAt(i, 1).toString());

                    if ( entityMgr.isOpen()) {
                        try {
                            Query q = entityMgr
                                    .createQuery("select o from Producto o " +
                                            "where trim(o.id) = :codigo");
                            q.setParameter("codigo", id.toString());
                            lista.add( (Producto) q.getSingleResult() );

                        }
                        catch (NoResultException  ignorada) {}
                        catch (Exception e) {
                            JOptionPane.showMessageDialog(this, "Error del sistema: [" +
                                    e.getMessage() + "]");
                            e.printStackTrace();
                        }
                    }

            }
        }
        return lista;
    }

 
    /*
     * Se encarga de llenar el ComboBox con los tipos
     * 
     */
    private void llenarCBTipo() {
        tipoComboBox.removeAllItems();
        if ( entityMgr.isOpen()) {
                try {
                        javax.persistence.Query q = entityMgr.createNamedQuery("Tipoproducto.findAll");
                        List<Tipoproducto> result = q.getResultList();

                        for (Tipoproducto t: result){
                            tipoComboBox.addItem(t);
                            Tipoproducto test = (Tipoproducto) tipoComboBox.getItemAt(tipoComboBox.getItemCount()-1);
                            System.out.println(test.getId());                                
                        }
                }
                catch (NoResultException  ignorada) {}
                catch (Exception e) {
                    JOptionPane.showMessageDialog(this, "Error del sistema: [" +
                            e.getMessage() + "]");
                    e.printStackTrace();
                }     
        }
    }
}
